package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.mess.DownOrUpMess;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-18 16:48
 */
@Component
@Slf4j
public class KafkaMessListener {
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @KafkaListener(topics = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
    public void downOrUp(String msg){

        if(StringUtils.isNotBlank(msg)){
            //1.将msg消息转换成实体类
            DownOrUpMess downOrUpMess = JSON.parseObject(msg, DownOrUpMess.class);
            if(downOrUpMess.getEnable() == null || downOrUpMess.getArticleId() == null){
                log.error("消息接收到数据不完整" + msg);
                return;
            }

            Short enable = downOrUpMess.getEnable(); //1上架 0下架
            //2.更新到数据库
            apArticleConfigMapper.update(null, Wrappers.<ApArticleConfig>lambdaUpdate()
                    .eq(ApArticleConfig::getArticleId,downOrUpMess.getArticleId())
                    .set(ApArticleConfig::getIsDown,enable == 0?1:0)
            );
        }

    }
}
